<?php

function populate_articles_route()
{
    register_rest_route('submit', 'articles', array(
        'methods' => 'POST',
        'callback' => 'populate_articles',
        'permission_callback' => '__return_true'
    ));
}

add_action('rest_api_init', 'populate_articles_route');

function populate_articles(WP_REST_Request $request)
{

    if ($request['pass'] !== 'king321321') {
        return ['error' => 'password error'];
    }

    $title = wp_strip_all_tags($request['title']);

    $chinese_preview_url = $request['chinese-preview-url'];

    $short_description = $request['short-description'];

    $download_url = $request["download-uri"];

    $resource_name = $request['product_name'];

    $version = $request['version'];

    $sliders = [
        'pi1' => $request['product_image1'],
        'pi2' => $request['product_image2'],
        'pi3' => $request['product_image3'],
        'pi4' => $request['product_image4'],
        'pi5' => $request['product_image5'],
        'pi6' => $request['product_image6']
    ];

    $post_id = wp_insert_post(array(
        'post_title' => $title,
        'post_content' => $request['content'],
        'post_status' => 'publish',
        'post_author' => 1,
        'post_category' => explode(",", $request['category']),
        'post_name' => $request['permalink'],
        'post_excerpt' => $short_description,
        'page_template' => $request['template'],
    ));

    if (isset($request['tags'])) {
        $tags = explode(',', $request['tags']);
        wp_set_post_terms($post_id, $tags, 'post_tag', true);
    }

    if ($post_id) {
        update_post_meta($post_id, "theme_short_desc", $short_description);
        update_post_meta($post_id, "description", $short_description);

        if(isset($download_url)){
            $attachment_id = upload_to_media_library_and_get_attachment_id($post_id, $download_url);
            $attachment_metadata = wp_get_attachment_metadata($attachment_id);
            if(isset($attachment_metadata['filesize'])){
                $file_size_mb = $attachment_metadata['filesize'] / 1048576;
                $leave_two_decimals = number_format($file_size_mb, 2);
            }

            $post_down_info = [
                ['name' => $resource_name, 'url' => wp_get_attachment_url($attachment_id), 'pwd' => '', 'version' => $version, 'date' => date('Y-m-d'), 'filesize' => $leave_two_decimals??0]
            ];

            add_post_meta($post_id, 'cao_downurl_new', $post_down_info);
        }
    }

    if (isset($chinese_preview_url)) {
        update_post_meta($post_id, "theme_url", $request['preview-url']);
        update_post_meta($post_id, "cao_demourl", $request['preview-url']);
        update_post_meta($post_id, "theme_preview_url", $chinese_preview_url);
    }

    update_post_meta($post_id, "post_titie", $title);

    if (!empty($request['dashboard-url'])) {
        update_post_meta($post_id, "dashboard_url", $request['dashboard-url']);
    }

    if (!empty($request['preview-url'])) {
        update_post_meta($post_id, "official_url", $request['preview-url']);
    }

    if (!empty($request['virus-scan-url'])) {
        update_post_meta($post_id, "virus_report_url", $request['virus-scan-url']);
    }

    if (isset($request['theme'])) {
        update_post_meta($post_id, "price", $request['price']);
    }

    update_post_meta($post_id, "cao_price", 29);
    update_post_meta($post_id, "cao_vip_rate", 0.1);

    if (isset($request['featured_image'])) {

        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        $tmp = download_url($request['featured_image']);

        if (is_wp_error($tmp)) {
            // handle error
            return $tmp->get_error_message();
        }

        $file_array = array(
            'name' => basename($request['featured_image']),
            'tmp_name' => $tmp
        );

        $attachment_id = media_handle_sideload($file_array, $post_id);

        // Set the featured image
        set_post_thumbnail($post_id, $attachment_id);

//        foreach ($sliders as $key => $value) {
//            if (!empty($value)) {
//
//                $attachment_id = upload_to_media_library_and_get_attachment_id($post_id, $value);
//
//                $attachment_id_array[] = $attachment_id;
//            }
//        }

//        if (count($attachment_id_array) > 0) {
//            $ais = implode(",", $attachment_id_array);
//            update_post_meta($post_id, "theme_gallery", $ais);
//        }

        $ais = implode(",", [$attachment_id]);
        update_post_meta($post_id, "theme_gallery", $ais);
    }

    //handle all image urls in the content section
    preg_match_all('/<img\s+.*?src=[\'"]([^\'"]+)[\'"].*?>/i', $request['content'], $matches);

    $image_urls = $matches[1];

    if (isset($image_urls) && !empty($image_urls)) {

        foreach ($image_urls as $url) {
            // Download the image
            $attached_id = upload_to_media_library_and_get_attachment_id($post_id, $url);

            // Get the URL of the image in the media library
            $attachment_url = wp_get_attachment_url($attached_id);

            // Replace the original URL with the URL of the image in the media library
            $request['content'] = str_replace($url, $attachment_url, $request['content']);
        }

        $result = wp_update_post([
            'ID' => $post_id,
            'post_content' => $request["content"]
        ]);

        return [
            'result' => $result
        ];
    }
    return [
        'post_id' => $post_id
    ];

}


function upload_to_media_library_and_get_attachment_id($post_id, $file_url)
{
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/media.php');
    require_once(ABSPATH . 'wp-admin/includes/image.php');

    $tmp = download_url($file_url);

    if (is_wp_error($tmp)) {
        // handle error
        return $tmp->get_error_message();
    }

    $file_array = array(
        'name' => basename($file_url),
        'tmp_name' => $tmp
    );

    $attachment_id = media_handle_sideload($file_array, $post_id);

    return $attachment_id;

}
